<?php

namespace Pw\MainBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Pw\MainBundle\Form\Type\TalentType;
use Pw\MainBundle\Form\Type\TalentEditType;
use Pw\MainBundle\Entity\Talent;
class TalentController extends Controller
{
    public function indexAction(){
		$em = $this->getDoctrine()->getManager();
		$talents = $em->getRepository('PwMainBundle:Talent')->findAll();
		return $this->render('PwMainBundle:Talent:index.html.php',  array('talents' => $talents));
    }
	public function addAction(){
		$em = $this->getDoctrine()->getManager();
		$talent = new Talent();
		$form = $this->createForm(new TalentType(), $talent, array('em' => $em));
		$request = $this->getRequest();
		if ($request->isMethod('POST')) {
			$form->bind($request);
			if ($form->isValid()) {
				$em = $this->getDoctrine()->getManager();
//				$talent->doUpload();
//				$em->persist($talent);
//				$em->flush();
//				return $this->redirect($this->generateUrl('talents_show'));
				var_dump($talent);
			}
		}
		return $this->render('PwMainBundle:Talent:add.html.php',  array('form' => $form->createView()));	
	}

	public function editAction($talentId){
		$em = $this->getDoctrine()->getEntityManager();
		$talent = $em->getRepository('PwMainBundle:Talent')->find($talentId);
		if ($talent) {
			$form = $this->createForm(new TalentEditType(), $talent, array('em' => $em));
			$request = $this->getRequest();		
			if ($request->isMethod('POST')) {
				$form->bind($request);
				if ($form->isValid()) {
					$talent->doUpload();
					$em->flush();
					return $this->redirect($this->generateUrl('talents_show'));
				}
			}
			return $this->render('PwMainBundle:Talent:edit.html.php',  array('form' => $form->createView(), 'talentId' => $talentId));
		}
		throw $this->createNotFoundException();
	}
	public function deleteAction($talentId){
		$em = $this->getDoctrine()->getEntityManager();
		$talent = $em->getRepository('PwMainBundle:Talent')->find($talentId);
		if ($talent) {
			$em->remove($talent);
			$em->flush();
		}
		return $this->redirect($this->generateUrl('talents_show'));
	}
	public function getJsonAction($talentId){
		$em = $this->getDoctrine()->getEntityManager();
		$result = array();
		if ($talentId) {
			$talent = $em->getRepository('PwMainBundle:Talent')->find($talentId);		
			if ($talent) {
				$result = $talent->getArray4JSON();
//				if ($rarity = $talent->getRarity()) {
//					$result['rarity'] = $rarity->getArray4JSON();
//				}	
			}
		} else {
			$talents = $em->getRepository('PwMainBundle:Talent')->findAll();
			foreach ($talents as $t) {
				$id = $t->getId();
				$result[$id] = $t->getArray4JSON();
//				if ($rarity = $t->getRarity()) {
//					$result[$id]['rarity'] = $rarity->getArray4JSON();
//				}	
			}
		}
		return new JsonResponse($result);
	}
}
